import subprocess as sp
import os
import cPickle

class SvmWrap:
    
    def __init__(self):
        self.dict = {}
        self.act = (0,1,1)

    def train(self):
        self.convertTrain()
        p = sp.Popen('svm-scale -l 0 -u 1 -s range trainData > trainData.scale', shell=True)
        p.wait()
        p = sp.Popen('python grid.py trainData.scale > params.txt', shell=True)
        p.wait()
        f = open('params.txt', 'r')
        l = f.readlines()
        f.close()
        print len(l)
        s = l[-1]
        r = s.split()
        cmd = 'svm-train -c '+str(r[0])+' -g '+str(r[1])+' trainData.scale'
        print cmd
        p = sp.Popen(cmd, shell=True)
        p.wait()

    def predict(self,frame):
        self.convertTest(frame)
        p = sp.Popen('/scratch/kinect/svm-scale -r /scratch/kinect/range '+ \
                '/scratch/kinect/testData > /scratch/kinect/testData.scale', shell=True)
        p.wait()
        p = sp.Popen('/scratch/kinect/svm-predict /scratch/kinect/testData.scale '+ \
            '/scratch/kinect/trainData.scale.model /scratch/kinect/data.predict > /dev/null', shell=True)
        p.wait()
        f = open('/scratch/kinect/data.predict','r')
        l = f.readlines()
        f.close()
        return self.dict[int(l[0])]


    def convertTrain(self):
        count = 0
        incr = 1
        self.dict = {}

        train = open('trainData', 'w')

        for g in os.listdir('data/'):
            n = g.split('.')[0]
            if len(n) == 0:
                continue
            self.dict[count] = n
            data = cPickle.load(open('data/'+ g))
            x = len(data) / 10
            for i in data[x:]:
                train.write(str(count)+' ')
                fc = 1
                for j in range(len(self.act)):
                    if self.act[j]:
                        for k in i[j]:
                            train.write(str(fc)+':'+str(k)+' ')
                            fc += 1
                train.write('\n')
            count += incr

        train.close()

    def convertTest(self,frame):
        test = open('/scratch/kinect/testData', 'w')
        test.write(str(0)+' ')
        fc = 1
        for j in range(len(self.act)):
            if self.act[j]:
                for k in frame[j]:
                    test.write(str(fc)+':'+str(k)+' ')
                    fc += 1
        test.write('\n')
        test.close()

def setupSvm():
    if not os.path.isdir('/scratch/kinect'):
        p = sp.Popen('mkdir /scratch/kinect/')
        p.wait()
    p = sp.Popen('cp range /scratch/kinect/',shell=True)
    p.wait()
    p = sp.Popen('cp trainData.scale.model /scratch/kinect/',shell=True)
    p.wait()
    p = sp.Popen('cp svm-predict /scratch/kinect/',shell=True)
    p.wait()
    p = sp.Popen('cp svm-scale /scratch/kinect/',shell=True)
    p.wait()
    p = sp.Popen('cp libsvm.so.2 /scratch/kinect/',shell=True)
    p.wait()

def main():
    svm = SvmWrap()
    svm.train()
    f = open('svm.model','w')
    cPickle.dump(svm,f)
    f.close()

if __name__ == "__main__":
    main()
